<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class SystemController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth.api');
    }

    /**
     * 获取系统信息
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function info()
    {
        $data = [
            'system' => [
                'php_version' => PHP_VERSION,
                'laravel_version' => app()->version(),
                'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
                'server_os' => PHP_OS,
            ],
            'database' => [
                'connection' => config('database.default'),
                'version' => $this->getDatabaseVersion(),
            ],
            'cache' => [
                'driver' => config('cache.default'),
                'status' => $this->checkCacheStatus(),
            ],
            'redis' => [
                'status' => $this->checkRedisStatus(),
            ],
            'websocket' => [
                'enabled' => config('websocket.enabled', false),
                'ws_url' => config('websocket.enabled', false) ? config('websocket.ws_url', 'ws://localhost:8080') : null,
            ],
            'time' => [
                'server_time' => now()->format('Y-m-d H:i:s'),
                'timezone' => config('app.timezone'),
            ],
        ];

        return $this->success($data, '获取成功');
    }

    /**
     * 获取数据库版本
     *
     * @return string
     */
    protected function getDatabaseVersion(): string
    {
        try {
            $version = DB::select('SELECT VERSION() as version');
            return $version[0]->version ?? 'Unknown';
        } catch (\Exception $e) {
            return 'Unknown';
        }
    }

    /**
     * 检查缓存状态
     *
     * @return string
     */
    protected function checkCacheStatus(): string
    {
        try {
            Cache::put('health_check', 'ok', 10);
            return Cache::get('health_check') === 'ok' ? '正常' : '异常';
        } catch (\Exception $e) {
            return '异常';
        }
    }

    /**
     * 检查 Redis 状态
     *
     * @return string
     */
    protected function checkRedisStatus(): string
    {
        try {
            Redis::ping();
            return '正常';
        } catch (\Exception $e) {
            return '异常';
        }
    }

    /**
     * 清除缓存
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function clearCache()
    {
        try {
            Cache::flush();
            return $this->success(null, '缓存清除成功');
        } catch (\Exception $e) {
            return $this->error('缓存清除失败：' . $e->getMessage(), 500);
        }
    }

    /**
     * 获取统计数据
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function statistics()
    {
        $data = [
            'users' => [
                'total' => \App\Models\User::count(),
                'enabled' => \App\Models\User::enabled()->count(),
                'disabled' => \App\Models\User::disabled()->count(),
            ],
            'roles' => [
                'total' => \App\Models\Role::count(),
                'enabled' => \App\Models\Role::enabled()->count(),
            ],
            'menus' => [
                'total' => \App\Models\Menu::count(),
                'enabled' => \App\Models\Menu::enabled()->count(),
            ],
            'departments' => [
                'total' => \App\Models\Department::count(),
                'enabled' => \App\Models\Department::enabled()->count(),
            ],
            'online_users' => \App\Models\OnlineUser::count(),
            'operation_logs' => \App\Models\OperationLog::count(),
            'login_logs' => \App\Models\LoginLog::count(),
        ];

        return $this->success($data, '获取成功');
    }
}

